
package com.crowdfunding.circle.question.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.crowdfunding.circle.analyze.entity.ProjectAnalyzeVO;
import com.crowdfunding.circle.analyze.param.ProjectAnalyzeParam;
import com.crowdfunding.circle.analyze.service.ProjectAnalyzeService;
import com.crowdfunding.circle.common.controller.BaseController;
import com.crowdfunding.circle.common.param.SessionUserInfo;
import com.crowdfunding.circle.question.entity.QuestionVO;
import com.crowdfunding.circle.question.param.QuestionParam;
import com.crowdfunding.circle.question.service.QuestionService;

/**
 * 你问我答Controller
 *
 * @author 朱国军
 * @since 1.0
 * @version 2015年12月27日 朱国军
 */
@Controller
public class QuestionController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(QuestionController.class);

    @Autowired
    private QuestionService questionService;

    @Autowired
    private ProjectAnalyzeService analyzeService;

    private final static String LIST_PAGE = "/question/question_list_ajax";
    
    private final static String ADMIN_LIST_PAGE = "/admin/question_manage";

    private final static String ACCOUNT_ANSWER_LIST_PAGE = "/account/my_answer";

    private final static String ACCOUNT_EAVESDROP_LIST_PAGE = "/account/my_eavesdrop";

    private final static String ACCOUNT_LIST_PAGE = "/account/my_question";

    private final static String VIEW_PAGE = "/question/question_view";

    private final static String ADMIN_VIEW_PAGE = "/question/question_admin_view";
    
    private final static String ACCOUNT_VIEW_PAGE = "/question/question_account_view";

    private final static String UPDATE_PAGE = "/question/question_edit";
    
    private final static String ANSWER_USER_LIST_PAGE = "/question/answer_user_list_ajax";
    
    private final static String ANSWER_PAGE = "/question/question_answer";
    
    @RequestMapping(value = "/check/question/toInsert")
    public ModelAndView intoInsert(String answerUser, String answerUserName) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        QuestionVO questionVO = new QuestionVO();

        questionVO.setAnswerUser(answerUser);
        questionVO.setAnswerUserName(answerUserName);

        resultMap.put("question", questionVO);
        return new ModelAndView(UPDATE_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/check/question/toUpdate/{id}")
    public ModelAndView intoUpdate(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> questionVO = questionService.findById(id, null);
        resultMap.put("question", questionVO);
        return new ModelAndView(UPDATE_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/check/question/toAnswer/{id}")
    public ModelAndView intoAnswer(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> questionVO = questionService.findById(id, null);
        resultMap.put("question", questionVO);
        return new ModelAndView(ANSWER_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/check/question/answer", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String answer(QuestionVO questionVO) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String validMsg = questionVO.valid();
        if (StringUtils.isNotBlank(validMsg)) {
            resultMap.put("result", false);
            resultMap.put("message", validMsg);
            return JSONObject.toJSONString(resultMap);
        }

        if (StringUtils.isBlank(questionVO.getAnswerDetail())) {
            resultMap.put("result", false);
            resultMap.put("message", "回答问题是回答内容不能为空");
            return JSONObject.toJSONString(resultMap);
        } else {
            questionVO.setQuestionStatus(3);
            questionVO.setAnswerTime(new Date(System.currentTimeMillis()));
        }
        
        try {
            Integer affectCount = 0;

            affectCount = questionService.update(questionVO);
            
            if (affectCount != null && affectCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "新增或修改你问我答成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "新增或修改你问我答失败");
            }
            
            Integer questionCount = questionService.queryQuerstionCount(seUser.getUserId());

            session.setAttribute("questionCount", questionCount);
            
        } catch (Exception e) {
            logger.error("新增或修改你问我答出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "新增或修改你问我答出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }
    
    @RequestMapping(value = "/check/question/update", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String update(QuestionVO questionVO) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");

        Map<String, Object> resultMap = new HashMap<String, Object>();
        String validMsg = questionVO.valid();
        if (StringUtils.isNotBlank(validMsg)) {
            resultMap.put("result", false);
            resultMap.put("message", validMsg);
            return JSONObject.toJSONString(resultMap);
        }
        
        try {
            Integer affectCount = 0;

            if (questionVO != null && StringUtils.isNotBlank(questionVO.getQuestionId())) {
                affectCount = questionService.update(questionVO);
            } else if (questionVO != null) {
                questionVO.setQuestionId(UUID.randomUUID().toString());
                questionVO.setPublishUser(seUser.getUserId());
                questionVO.setDataStatus(0);
                questionVO.setQuestionStatus(1);
                affectCount = questionService.insert(questionVO);
            }
            
            if (affectCount != null && affectCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "新增或修改你问我答成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "新增或修改你问我答失败");
            }
        } catch (Exception e) {
            logger.error("新增或修改你问我答出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "新增或修改你问我答出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }
    
    @RequestMapping(value = "/admin/question/delete/{id}", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String delete(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Integer deleteCount = questionService.delete(id);
            if (deleteCount != null && deleteCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "删除你问我答成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "删除你问我答失败");
            }
        } catch (Exception e) {
            logger.error("删除你问我答出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "删除你问我答出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }

    @RequestMapping(value = "/admin/question/list")
    public ModelAndView queryAdminList(QuestionParam questionParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<QuestionVO> dataList = questionService.queryByPage(questionParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", questionParam);
        return new ModelAndView(ADMIN_LIST_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/uncheck/question/list")
    public ModelAndView queryList(QuestionParam questionParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        questionParam.setListStatus(1);

        List<QuestionVO> dataList = questionService.queryByPage(questionParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", questionParam);
        return new ModelAndView(LIST_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/account/question/list")
    public ModelAndView queryAccountList(QuestionParam questionParam) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        questionParam.setPublishUser(seUser.getUserId());
        List<QuestionVO> dataList = questionService.queryByPage(questionParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", questionParam);
        return new ModelAndView(ACCOUNT_LIST_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/account/question/answerList")
    public ModelAndView queryAnserrList(QuestionParam questionParam) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        questionParam.setAnswerUser(seUser.getUserId());
        if (questionParam.getQuestionStatus() == null || questionParam.getQuestionStatus() == 0) {
            questionParam.setQuestionStatus(2);
        }
        List<QuestionVO> dataList = questionService.queryByPage(questionParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", questionParam);
        return new ModelAndView(ACCOUNT_ANSWER_LIST_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/account/question/eavesdropList")
    public ModelAndView queryEavesdropList(QuestionParam questionParam) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        questionParam.setBuyUser(seUser.getUserId());
        List<QuestionVO> dataList = questionService.queryByPage(questionParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", questionParam);
        return new ModelAndView(ACCOUNT_EAVESDROP_LIST_PAGE, resultMap);
    }

    @RequestMapping(value = "/uncheck/answerUser/list")
    public ModelAndView queryAnswerUserList(QuestionParam questionParam) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        if (seUser != null && StringUtils.isNotBlank(seUser.getUserId())) {
            questionParam.setAnswerUser(seUser.getUserId());
        }

        List<Map<String, Object>> dataList = questionService.queryAnswerUserByPage(questionParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", questionParam);
        return new ModelAndView(ANSWER_USER_LIST_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/uncheck/question/view/{id}")
    public ModelAndView viewConfigInfo(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> questionVO = questionService.findById(id, null);
        resultMap.put("question", questionVO);
        
        ProjectAnalyzeParam analyzeParam = new ProjectAnalyzeParam();

        analyzeParam.setPublishUser(questionVO.get("answerUser").toString());
        analyzeParam.setPageSize(Integer.MAX_VALUE);
        analyzeParam.setChargeState(1);
        List<ProjectAnalyzeVO> freeList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("freeList", freeList);
        
        analyzeParam.setChargeState(2);
        List<ProjectAnalyzeVO> partlyFreeList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("partlyFreeList", partlyFreeList);
        
        analyzeParam.setChargeState(3);
        List<ProjectAnalyzeVO> chargeList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("chargeList", chargeList);
        
        resultMap.put("discussType", 3);

        resultMap.put("discussTargetId", questionVO.get("questionId").toString());

        return new ModelAndView(VIEW_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/admin/question/view/{id}")
    public ModelAndView adminView(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> questionVO = questionService.findById(id, null);
        resultMap.put("question", questionVO);
        
        ProjectAnalyzeParam analyzeParam = new ProjectAnalyzeParam();

        analyzeParam.setPublishUser(questionVO.get("answerUser").toString());
        analyzeParam.setPageSize(Integer.MAX_VALUE);
        analyzeParam.setChargeState(1);
        List<ProjectAnalyzeVO> freeList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("freeList", freeList);
        
        analyzeParam.setChargeState(2);
        List<ProjectAnalyzeVO> partlyFreeList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("partlyFreeList", partlyFreeList);
        
        analyzeParam.setChargeState(3);
        List<ProjectAnalyzeVO> chargeList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("chargeList", chargeList);
        
        resultMap.put("discussType", 3);

        resultMap.put("discussTargetId", questionVO.get("questionId").toString());

        return new ModelAndView(ADMIN_VIEW_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/account/question/view/{id}")
    public ModelAndView accountView(@PathVariable String id) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");

        Map<String, Object> resultMap = new HashMap<String, Object>();
        Map<String, Object> questionVO = questionService.findById(id, seUser.getUserId());
        resultMap.put("question", questionVO);
        
        if (StringUtils.equals(questionVO.get("publishUser").toString(), seUser.getUserId())) {
            questionVO.put("buyCount", 1000);
        } else if (StringUtils.equals(questionVO.get("answerUser").toString(), seUser.getUserId())) {
            questionVO.put("buyCount", 2000);
        }
        
        ProjectAnalyzeParam analyzeParam = new ProjectAnalyzeParam();

        analyzeParam.setPublishUser(questionVO.get("answerUser").toString());
        analyzeParam.setPageSize(Integer.MAX_VALUE);
        analyzeParam.setChargeState(1);
        List<ProjectAnalyzeVO> freeList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("freeList", freeList);
        
        analyzeParam.setChargeState(2);
        List<ProjectAnalyzeVO> partlyFreeList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("partlyFreeList", partlyFreeList);
        
        analyzeParam.setChargeState(3);
        List<ProjectAnalyzeVO> chargeList = analyzeService.queryByPage(analyzeParam);
        resultMap.put("chargeList", chargeList);
        
        resultMap.put("discussType", 3);

        resultMap.put("discussTargetId", questionVO.get("questionId").toString());

        return new ModelAndView(ACCOUNT_VIEW_PAGE, resultMap);
    }
}
